define([], function () {
    return ['$scope', '$filter', '$stateParams', 'config', 'MMWService', '$rootScope','$timeout',
        function ($scope, $filter, $stateParams, config, $MMWService, $rootScope, $timeout) {
            // 20220926 modify by chenshibo for#118836：增加分页
            $scope.PageConfig = { page: 0, page_count: 50 };
            $scope.pcs_filter = {};
            // 20230912 modify by shiwl for#0145788：增加分页
             $scope.dispatch_filter = {};
            $scope.init = function () {
                $scope.condition = {
                    plot_no: '',
                    serial_number_start: '',
                    serial_number_end: '',
                    factory: 1
                };
                $scope.pcs_detail = [];
            };

            $scope.back = function () {
                $scope.$root.changeProgram('home', true);
            };

            $scope.loadPlotList = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: 29,
                    pageRecord: 50,
                    condition: [
                        { name: $filter('translate')('common.queryList.plot_no'), column_name: 'lotno', query_mode: '2', value: $scope.condition.plot_no, merge_condition_model: 'AND' }
                    ],
                    header: [
                        { label: $filter('translate')('common.queryList.plot_no'), code: 'page_no' },
                        { label: $filter('translate')('common.queryList.wo_c'), code: 'wono' },
                        { label: $filter('translate')('common.queryList.item_c'), code: 'productno' },
                        { label: $filter('translate')('common.queryList.item_n'), code: 'productname' },
                        { label: $filter('translate')('common.queryList.item_spec'), code: 'itemspec' }
                    ],
                    setCondition: function (conditions) {
                        conditions.push({ column_name: 'status', query_mode: $scope.condition.factory, value: '11', merge_condition_model: 'AND' });
                        return conditions;
                    },
                    selectCode: $scope.condition.plot_no,
                    confirm: function (selectItem) {
                        $scope.condition.plot_no = selectItem.page_no;
                    }
                });
            };

            $scope.search = function () {
                var msg = checkCondtions();
                if (msg === '') {
                    serial_number_generation_info_get($scope.condition);
                } else {
                    $scope.$root.showAlert(msg);
                }
            };

            $scope.serialPreview = function () {
                var msg = '';
                if ($scope.condition.plot_no == '') {
                    msg += $filter('translate')('E03.msg.plot_no_empty');
                }

                if (msg === '') {
                    serial_number_pre_display_get($scope.condition);
                } else {
                    $scope.$root.showAlert(msg);
                }
            };

            $scope.selectAll = function () {
                $scope.$root.showLoading();
                $scope.isSelectAll = !$scope.isSelectAll;
                if ($scope.pcs_detail && $scope.pcs_detail.length > 0) {
                    $scope.pcs_detail.forEach(function (pcs) {
                        pcs.isSelect = $scope.isSelectAll + '';
                    });
                }
                $scope.$root.hideLoading();
            };

            $scope.itemClick = function (item) {
                item.isSelect = (item.isSelect == 'true' ? 'false' : 'true');
                if (item.isSelect == 'false') {
                    $scope.isSelectAll = false;
                }
            };

            $scope.confirm = function () {
                serial_number_process_json($scope.condition.plot_no, function (data) {
                    //data
                    $scope.$root.showToast($filter('translate')('E03.msg.success'));
                    $scope.search();
                    //20230114 add by summerteng for M#125486: 已經發版, 不可新加dll, 調整為新舊融合
                    if(data.pcs_detail.length > 0)
                    {
                        if(data.runcard_pdf_get && data.runcard_pdf_get.length > 0) {
                           //如果是PDF, 走新function
                           printPDF(data);
                        }
                        else
                        {
                           //如果是bartender走原本的printTag
                           printTag(data.pcs_detail, 0);         
                        }
                                
                    }
                });
            };
            //分頁
            $scope.getPages = function (list, PageConfig, filterItem) {
                if (list) {
                    var temp_list = list.filter(function (item, index, array) {
                        var isOK = true,
                            keys = Object.keys(filterItem);
                        for (var i = 0; i < keys.length; i++) {
                            var key = keys[i];
                            if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                    isOK = false;
                                    break;
                                }
                            }
                        }
                        return isOK;
                    });
                    if (PageConfig) {
                        if (temp_list.length != 0) {
                            PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count);

                            if (PageConfig.page >= PageConfig.total_page) {
                                PageConfig.page = 0;
                            }
                            var index = PageConfig.page * PageConfig.page_count;
                            return temp_list.slice(index, index + PageConfig.page_count);
                        } else {
                            PageConfig.total_page = 1;
                            PageConfig.page = 0;
                        }
                    } else {
                        return temp_list;
                    }
                } else {

                    return list;
                }
            };


            function checkCondtions() {
                var msg = '';
                if ($scope.condition.plot_no == '') {
                    msg += $filter('translate')('E03.msg.plot_no_empty');
                } else if (($scope.condition.serial_number_start + $scope.condition.serial_number_end) != '') {
                    if ($scope.condition.serial_number_start == '' || $scope.condition.serial_number_end.length == '') {
                        msg += $filter('translate')('E03.msg.serial_no_not_enough');    //起始序號未填寫完整
                    } else if (isNaN($scope.condition.serial_number_start) || isNaN($scope.condition.serial_number_end)) {
                        msg += $filter('translate')('E03.msg.serial_no_illegal');   //成品序號格式錯誤
                    } else if (+$scope.condition.serial_number_start > +$scope.condition.serial_number_end) {
                        msg += $filter('translate')('E03.msg.serial_no_start_less_than_end'); //起始序號不可大於結束序號
                    }
                }
                return msg;
            }

            function serial_number_generation_info_get(condition) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.serial_number_generation_info_get',
                    content: {
                        plot_no: condition.plot_no,
                        serial_number_start: condition.serial_number_start,
                        serial_number_end: condition.serial_number_end
                    },
                    success: function (data) {
                        $scope.generated = data.generated;
                        $scope.pcs_detail = data.pcs_detail;
                        create_max_detail = [];
                    }
                });
            }
            var create_max_detail = [];
            function serial_number_pre_display_get(condition) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.serial_number_pre_display_get',
                    content: {
                        plot_no: condition.plot_no,
                        serial_number_start: condition.serial_number_start,
                        serial_number_end: condition.serial_number_end
                    },
                    success: function (data) {
                        $scope.pcs_detail = data.pcs_detail;
                        create_max_detail = data.create_max_detail;
                    }
                });
            }

            function serial_number_process_json(plot_no, callback) {
                var pcs_detail_isselect = [];
                $scope.pcs_detail.forEach(function (item) {
                    if (item.isSelect == 'true') {
                        pcs_detail_isselect.push(item);
                    }
                });
                if (pcs_detail_isselect.length == 0) return
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.serial_number_process',
                    content: {
                        ip: config.server.ip,
                        port: config.server.port,
                        plot_no: plot_no,
                        pcs_detail: pcs_detail_isselect,
                        create_max_detail: create_max_detail,
                        // 20230419 add by 文蔚 for M# 0119702: [標準][DEV]序號管理-序列号打印-手動生成，生成與打印方開 
                        isGenerate:false
                    },
                    success: function (data) {
                        //$scope.pcs_detail = data.pcs_detail;
                        if (callback)
                            callback(data);
                    }
                });
            }

            function printTag(tags, index) {
                if (tags && index < tags.length) {
                    if (window.nodeRequire) {
                        var exec = window.nodeRequire('child_process').exec;
                        $rootScope.showToast($filter('translate')('E03.msg.prpare_print', { index: index }));
                        //20230114 add by summerteng for M#125486: 已經發版, 不可新加dll, 調整為新舊融合
                        exec(tags[index].commandline, function (error, stdout, stderr) {
                            if (error) {
                                $rootScope.showAlert($filter('translate')('E01.msg.cantprint'));
                            }
                            index = index + 1;
                            printTag(tags, index);
                        });
                    }
                }
            }
            //20230114 add by summerteng for M#125486: 已經發版, 不可新加dll, 調整為新舊融合
            function printPDF(data){
                if (data.runcard_pdf_get && data.runcard_pdf_get.length > 0) {
                     // 執行 PDF列印
                     if (data.runcard_pdf_get && data.runcard_pdf_get.length > 0) {
                         // 20201121 modify by 外包 for M#80272: 增加不同的标签可以多条打印的功能
                         let tempRuncardPdf = [];
                         data.runcard_pdf_get.forEach(r => {
                             if (r.printCount > 1) {
                                 for (var i = 0; i < r.printCount; i++) {
                                     tempRuncardPdf.push({
                                         url_pdf: r.url_pdf,
                                         printCount: 1
                                     });
                                 }
                             } else {
                                 tempRuncardPdf.push(r);
                             }
                         });
                         printBatch(tempRuncardPdf, 0);
                     }
                 } else {
                     // 自動打印
                     if (data.auto_runcard_pdf_get && data.auto_runcard_pdf_get.length > 0) {
                         // 20201110 modify by WeiTing for M#80602 - 增加多張列印功能(printCount)。
                         for (var i = 0; i < data.auto_runcard_pdf_get.length; i++) {
                             pdf_url = data.auto_runcard_pdf_get[0].url_pdf;
                             if (pdf_url.indexOf('http://') == -1) {
                                 pdf_url = 'http://' + config.server.ip + ':' + config.server.port + pdf_url;
                             }
                             print(pdf_url, data.runcard_pdf_get[i].printCount);
                         }
                     }
                     print(pdf_url);
                 }
             }

            // 批量打印
            function printBatch(runcard_pdf_get, index) {
                if (index < runcard_pdf_get.length) {
                    pdf_url = runcard_pdf_get[index].url_pdf;
                    if (pdf_url.indexOf('http://') == -1) {
                        pdf_url = 'http://' + config.server.ip + ':' + config.server.port + pdf_url;
                    }
                    // 20231120 modify by Alan for M#150724 - 增加方向判斷自動轉向
                    var width = runcard_pdf_get[index].width;
                    var height = runcard_pdf_get[index].height;
                    printNotSameBarcode(pdf_url, width, height, function callback() {
                        index = index + 1;
                        printBatch(runcard_pdf_get, index);
                    });
    
                }
            };
            
            // PDF列印
            function printNotSameBarcode(pdf_url, width, height, callback) {
                if (window.nodeRequire) {
                    var sumatraPDF = window.nodeRequire('sumatra-pdf');
                    if (sumatraPDF) {
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try {
                            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            RuncardPath = remote.app.getAppPath();
                        } catch (e) {
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath) + '\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if (!fs.existsSync(RuncardPath)) {
                            fs.mkdirSync(RuncardPath);
                        }

                        // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                        // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        fs.readdirSync(RuncardPath, (err, files) => {
                            if (err) {
                                console.log(err);
                            }
                            //listing all files using forEach
                            files.forEach((file) => {
                                // Do whatever you want to do with the file
                                fs.unlink(RuncardPath + '/' + file, (err) => {
                                    if (err) {
                                        console.debug(err);
                                    }
                                })
                            });
                        })
    
                        // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                        let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                        $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                            $rootScope.showLoading();
                            // 20201110 modify by WeiTing for M#80602 - 不跳列印介面，直接使用預設列印機進行列印(printToDefault)。
                            var _fn = sumatraPDF.printToDefault;
                            _fn({
                                path: dist_path,
                                settings: width > height ? 'landscape' : '',
                                success: function () {
                                    callback();
                                    $rootScope.hideLoading();
                                    $rootScope.showToast($filter('translate')('common.msg.success'));
                                },
                                error: function (error) {
                                    $rootScope.hideLoading();
                                    $rootScope.showToast($filter('translate')('common.msg.success'));
                                    //console.error(error);
                                }
                            });
                        });
                    } else {
                        window.frames['kmi-pdf-panel'].pdf_print();
                    }
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
            };
        }];
});
